package com.mediacloud.app.newsmodule.fragment.navigate;

import android.graphics.Color;
import android.os.Bundle;
import android.text.TextPaint;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.eventTrack.TXReportManager;
import com.flyco.tablayout.SlidingTabLayout;
import com.mediacloud.app.assembly.util.Utility;
import com.mediacloud.app.assembly.widget.RadioGroupX;
import com.mediacloud.app.fbnavsk.SecondFloorHandlerKt;
import com.mediacloud.app.model.OnVideoPause;
import com.mediacloud.app.model.fragment.INaviateState;
import com.mediacloud.app.model.news.CatalogItem;
import com.mediacloud.app.model.utils.AppModuleUtils;
import com.mediacloud.app.nav2.fragment.HqyNavFragment;
import com.mediacloud.app.newsmodule.R;
import com.mediacloud.app.reslib.enums.AppFactoryGlobalConfig;

import org.greenrobot.eventbus.EventBus;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.ArrayList;
import java.util.List;

/**
 * 所谓的三级导航
 */
@SuppressWarnings("ALL")
public class HammerNavigateSub extends HqyNavFragment implements INaviateState, IHammerNavigate4LBS, RadioGroupX.LayoutComplete {
    //    FragmentManager fragmentManager;
//    Fragment currentFragment;
    List<CatalogItem> childNavigates;
    CatalogItem catalogItem;
    //HorizontalScrollView ourScrollView;
    //RadioGroupX innerRadioGroup;
    // View mViewLine;
    //FrameLayout bottomFragment;
    //int currentIndex = 0;

    //三级导航样式配置
    protected int navigateHeight;
    protected String background_color;
    protected int spacing = 20;
    protected String navigate_show_selected_color;
    protected int navigate_show_selected_type;
    protected String navigate_show_unselected_color;
    protected int navigate_show_unselected_type;

    final int Mode_Text = 1;
    final int Mode_Img = 2;
    final int Mode_Rect = 3;
    int currentMode = Mode_Text;

    //XThirdContainer thirdContainer;
    private View tabbg;
    private SlidingTabLayout tabLayout;
    private ViewPager viewPager;
    private ArrayList<Fragment> fragments;

    //记录三级导航选中
    private int currentPos = 0;

    @Override
    public int getLayoutResID() {
        return R.layout.fragment_third_navigate;
    }

    @Override
    public void initView() {
        tabLayout = findViewById(R.id.tabLayout);
        tabbg = findViewById(R.id.tabbg);
        viewPager = findViewById(R.id.viewPager);
       /* thirdContainer = findViewById(R.id.thirdContainer);
        innerRadioGroup = findViewById(R.id.innerRadioGroup);
        innerRadioGroup.setLayoutComplete(this);
        ourScrollView = findViewById(R.id.ourScrollView);
        mViewLine = findViewById(R.id.mViewLine);
        bottomFragment = findViewById(R.id.bottomFragment);*/
        /*tabLayout.setOnTabSelectListener(new OnTabSelectListener() {

            @Override
            public void onTabSelect(int position) {
                for (int i = 0; i < tabLayout.getTabCount(); i++) {
                    TextView textView = tabLayout.getTitleView(i);
                    if (position == i) {
                        textView.setTypeface(Typeface.DEFAULT_BOLD);
                    } else {
                        textView.setTypeface(Typeface.DEFAULT);
                    }
                }
            }

            @Override
            public void onTabReselect(int position) {

            }
        });*/
        if (childNavigates != null && childNavigates.size() > 0) {
            try {
                if (!TextUtils.isEmpty(navigate_show_selected_color)) {
                    tabLayout.setIndicatorColor(Color.parseColor(navigate_show_selected_color));
                    tabLayout.setTextSelectColor(Color.parseColor(navigate_show_selected_color));
                }
                if (!TextUtils.isEmpty(navigate_show_unselected_color)) {
                    tabLayout.setTextUnselectColor(Color.parseColor(navigate_show_unselected_color));
                }
                if (spacing == 0) {
                    spacing = 20;
                }
                tabLayout.setTabPadding(spacing);
            } catch (Exception e) {

            }


            ArrayList<String> names = new ArrayList<>();
            fragments = new ArrayList<>();
            CatalogItem catalogItem1;
            for (int i = 0; i < childNavigates.size(); i++) {
                catalogItem1 = childNavigates.get(i);
                if (catalogItem1 != null) {
                    names.add(catalogItem1.getName());
                    fragments.add(AppModuleUtils.getViewContentFragment(getActivity(), childNavigates.get(i)));
                }
            }
            if (fragments.size() == 0) {
                tabLayout.setVisibility(View.GONE);
            } else {
                TextPaint textPaint = new TextPaint();
                textPaint.setTextSize(getResources().getDimensionPixelSize(R.dimen.dimen17));
                StringBuilder stringBuilder = new StringBuilder();
                for (int i = 0; i < names.size(); i++) {
                    stringBuilder.append(names.get(i));
                }
                float textsWidth=textPaint.measureText(stringBuilder.toString()) +getResources().getDimension(R.dimen.dimen5);
                float tabWidth = textsWidth+ names.size() * 2 * dp2px(spacing);
                viewPager.post(new Runnable() {
                    @Override
                    public void run() {
                        ViewGroup.LayoutParams params = tabLayout.getLayoutParams();
                        if (tabLayout.getWidth() < tabWidth) {
                            // tabLayout.setTabSpaceEqual(false);
                            params.width = ViewGroup.LayoutParams.MATCH_PARENT;
                            int p = (int) (getResources().getDimension(R.dimen.dimen12)-dp2px(spacing));
                            if(p>0){
                                tabLayout.setPadding(p,0,p,0);
                            }
                        } else {
                            //tabLayout.setTabSpaceEqual(true);
                            float spw =(tabLayout.getWidth()-textsWidth)/(names.size() * 2+2);
                            float tabWidth2=tabLayout.getWidth()-spw*2;
                            spacing=Utility.px2DP(getContext(),spw);
                            tabLayout.setTabPadding(spacing);
                            params.width = (int) tabWidth2;
                        }

                        tabLayout.setLayoutParams(params);
                    }
                });
                PagerAdapter pagerAdapter = new PagerAdapter(getChildFragmentManager(), fragments, names);
                viewPager.setAdapter(pagerAdapter);
                viewPager.setOffscreenPageLimit(fragments.size() / 2 + 1);
                viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                    @Override
                    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

                    }

                    @Override
                    public void onPageSelected(int position) {
                        TXReportManager.getInstance().app_jhapp_paper_thirdtab_switch(catalogItem.getName(),
                                childNavigates.get(currentPos).getName(),currentPos+1+"",
                                childNavigates.get(position).getName(),position+1+"","否");

                        currentPos = position;
                    }

                    @Override
                    public void onPageScrollStateChanged(int state) {

                    }
                });
                tabLayout.setViewPager(viewPager);
                tabLayout.setCurrentTab(0);
                tabLayout.setVisibility(View.VISIBLE);
            }

        } else {
            tabLayout.setVisibility(View.GONE);
        }
    }

    private float dp2px(int dpValue) {
        return (dpValue * getResources().getDisplayMetrics().density + 0.5f);
    }

    @Override
    protected void initArgs() {
        super.initArgs();
        catalogItem = getFragmentArguments().getParcelable("catalog");
        if (catalogItem != null && catalogItem.getCatalogItems() != null && catalogItem.getCatalogItems().size() > 0) {
            childNavigates = catalogItem.getCatalogItems();
        }
        if (childNavigates != null && childNavigates.size() > 0) {
            parseGrandChildNavigateStyle(catalogItem);
        }

        //fragmentManager = getChildFragmentManager();
    }

    static class PagerAdapter extends FragmentPagerAdapter {
        public ArrayList<Fragment> fragments;
        public ArrayList<String> strings;

        public PagerAdapter(@NonNull FragmentManager fm, ArrayList<Fragment> fragments, ArrayList<String> strings) {
            super(fm);
            this.fragments = fragments;
            this.strings = strings;
        }

        @NonNull
        @Override
        public Fragment getItem(int position) {
            return fragments.get(position);
        }

        @Override
        public int getCount() {
            return fragments.size();
        }

        @androidx.annotation.Nullable
        @Override
        public CharSequence getPageTitle(int position) {
            return strings.get(position);
        }
    }

    /**
     * 解析三级导航样式
     *
     * @param catalogItem
     */
    protected void parseGrandChildNavigateStyle(CatalogItem catalogItem) {
        if (catalogItem.getNavigate() != null && catalogItem.getNavigate().getThree_navigate() != null) {
            navigateHeight = catalogItem.getNavigate().getThree_navigate().getHeight();
            currentMode = catalogItem.getNavigate().getThree_navigate().getThree_navigate_type();
            background_color = catalogItem.getNavigate().getThree_navigate().getBackground_color();
            spacing = (int) (catalogItem.getNavigate().getThree_navigate().getNavigate_show_spacing()/3f);
            String mainColor = AppFactoryGlobalConfig.getAppServerConfigInfo(getActivity()).getColor();
            navigate_show_unselected_color = mainColor;
            navigate_show_selected_color = mainColor;
            if (catalogItem.getNavigate().getThree_navigate().getNavigate_show_unselected() != null) {
                //1默认主题色，2自定义颜色
                navigate_show_unselected_type = catalogItem.getNavigate().getThree_navigate().getNavigate_show_unselected().getType();
                if (navigate_show_unselected_type == 2)
                    navigate_show_unselected_color = catalogItem.getNavigate().getThree_navigate().getNavigate_show_unselected().getColor();
            }

            if (catalogItem.getNavigate().getThree_navigate().getNavigate_show_selected() != null) {
                //	1与未选中相同，2主题色，3自定义颜色
                navigate_show_selected_type = catalogItem.getNavigate().getThree_navigate().getNavigate_show_selected().getType();
                if (navigate_show_selected_type == 1)
                    navigate_show_selected_color = navigate_show_unselected_color;
                else if (navigate_show_selected_type == 3)
                    navigate_show_selected_color = catalogItem.getNavigate().getThree_navigate().getNavigate_show_selected().getColor();
            }
            return;
        }
    }

    @Override
    protected void initOther() {
        super.initOther();
    }

    @Override
    public void choosed() {
        /*if (currentFragment != null && currentFragment instanceof INaviateState) {
            ((INaviateState) currentFragment).choosed();
        }*/
        try {
            for (Fragment f : fragments) {
                if (f != null && f instanceof INaviateState) {
                    ((INaviateState) f).choosed();
                }
            }
        } catch (Exception e) {

        }
        if (getActivity() != null && !checkInited) {
            mRootView.postDelayed(new Runnable() {
                @Override
                public void run() {
                    showContent();
                }
            }, 500);
        }
    }

    @Override
    public void unChosoed() {
        try {
            for (Fragment f : fragments) {
                if (f != null && f instanceof INaviateState) {
                    ((INaviateState) f).unChosoed();
                }
            }
        } catch (Exception e) {

        }
        /*if (currentFragment != null && currentFragment instanceof INaviateState) {
            ((INaviateState) currentFragment).unChosoed();
        }*/
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        try {
            for (Fragment f : fragments) {
                if (f != null) {
                    f.onHiddenChanged(hidden);
                }
            }
        } catch (Exception e) {

        }
        //   if (currentFragment != null) currentFragment.onHiddenChanged(hidden);
    }

    @Override
    public void replaceLBSFragment(CatalogItem catalogItem, Fragment old, Fragment newFragment) {
        try {
            if (fragments != null && newFragment != null) {
                for (int i = 0; i < fragments.size(); i++) {
                    if (fragments.get(i) != null && newFragment.getClass().getCanonicalName().equals(fragments.get(i).getClass().getName())) {
                        viewPager.setCurrentItem(i);
                        return;
                    }
                }
            }

        } catch (Exception e) {

        }
        /*if (currentFragment != null) {
            try {
                fragmentManager = getChildFragmentManager();
                FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                if (currentFragment != null)
                    fragmentTransaction.remove(currentFragment).commitNowAllowingStateLoss();
                fragmentManager.executePendingTransactions();
                fragmentTransaction = fragmentManager.beginTransaction();
                currentFragment = newFragment;
                fragmentTransaction.replace(R.id.bottomFragment, currentFragment).commitAllowingStateLoss();
                fragmentManager.executePendingTransactions();
                if (currentIndex < childNavigates.size()) {
                    childNavigates.set(currentIndex, catalogItem);
                }
                if (currentMode == Mode_Text)
                    ((RadioButton) innerRadioGroup.getChildAt(currentIndex)).setText(catalogItem.getCatname());
                if (currentFragment instanceof INaviateState) {
                    ((INaviateState) currentFragment).choosed();
                }
                TXReportManager.getInstance().onThirdChannelTabEvent(childNavigates.get(currentIndex).getId(), childNavigates.get(currentIndex).getName());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }*/
    }

    protected void addItems() {
      /*  if (spacing == 0) {
            spacing = getActivity().getResources().getDimensionPixelOffset(R.dimen.dimen20);
        } else {
        }
        //三级导航高度（像素）图片时有效
        if (navigateHeight == 0) {
            navigateHeight = getResources().getDimensionPixelSize(R.dimen.dimen40);
        } else {
            if (!Utility.isAdMachine(getActivity())) {
                navigateHeight = Utility.dpToPx(getActivity(), navigateHeight / 3.0f);
            }
        }
        if (currentMode == Mode_Text) {
            bottomFragment.setPadding(0, 0, 0, 0);
            HorizontalScrollView.LayoutParams params = (HorizontalScrollView.LayoutParams) innerRadioGroup.getLayoutParams();
            params.height = getResources().getDimensionPixelSize(R.dimen.dimen40);
            innerRadioGroup.setLayoutParams(params);
        }
        for (int i = 0; i < childNavigates.size(); i++) {
            RadioGroup.LayoutParams lp = null;
            if (currentMode == Mode_Rect) {
                if (i + 1 > catalogItem.getNavigate().getThree_navigate().getNavigate_num()) {
                    break;
                }
                lp = new RadioGroup.LayoutParams(RadioGroup.LayoutParams.WRAP_CONTENT, getActivity().getResources().getDimensionPixelOffset(R.dimen.dimen28));
            } else {
                lp = new RadioGroup.LayoutParams(RadioGroup.LayoutParams.WRAP_CONTENT, RadioGroup.LayoutParams.MATCH_PARENT);
            }
            final RadioButton4ThirdNavigate radioButton4ThirdNavigate = new RadioButton4ThirdNavigate(getActivity());
            lp.gravity = Gravity.CENTER;
            final CatalogItem catalogItem = childNavigates.get(i);
            radioButton4ThirdNavigate.setButtonDrawable(new ColorDrawable(Color.TRANSPARENT));
            if (currentMode == Mode_Text || currentMode == Mode_Rect) {
                if (childNavigates.size() == 1)//只有一个且为文本时候不要去设置Padding 不然不会居中
                    spacing = 0;
                radioButton4ThirdNavigate.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimension(R.dimen.dimen14));
                radioButton4ThirdNavigate.setText(catalogItem.getCatname());
                if (currentMode == Mode_Rect) {
                    mViewLine.setVisibility(View.GONE);
                    int dimen22 = getActivity().getResources().getDimensionPixelOffset(R.dimen.dimen22);
                    int dimen16 = getActivity().getResources().getDimensionPixelOffset(R.dimen.dimen16);
                    //bug49379 不加边距
                    radioButton4ThirdNavigate.setPaddingRelative(dimen16, 0, dimen16, 0);
                    if (i == 0) {
                        lp.setMargins(0, 0, dimen22, 0);
                    } else {
                        lp.setMargins(dimen22, 0, dimen22, 0);
                    }
                } else radioButton4ThirdNavigate.setPaddingRelative(spacing, 0, spacing, 0);
            } else if (currentMode == Mode_Img) {

                mViewLine.setVisibility(View.GONE);
                String defaultIcon = catalogItem.getIcon() != null && catalogItem.getIcon().size() > 0 ? catalogItem.getIcon().get(0) : "";
                String CheckedIcon = catalogItem.getIcon() != null && catalogItem.getIcon().size() > 1 ? catalogItem.getIcon().get(1) : "";
                radioButton4ThirdNavigate.index = i;
                ImageSize imageSize = radioButton4ThirdNavigate.setNoralUrl(defaultIcon, new int[]{catalogItem.getIcon_width(), catalogItem.getIcon_height()}, navigateHeight);

                radioButton4ThirdNavigate.setCheckedUrl(CheckedIcon, new int[]{catalogItem.getIcon_width(), catalogItem.getIcon_height()}, navigateHeight);

                lp.width = imageSize.getWidth();
                lp.height = imageSize.getHeight();
                radioButton4ThirdNavigate.initDefault(AppFactoryGlobalConfig.getDefaultImagLoadBackground(), AppFactoryGlobalConfig.getDefaultImageLoadDrawable(), lp.width / (lp.height * 1.0f));
                radioButton4ThirdNavigate.setMinWidth(lp.width);
                radioButton4ThirdNavigate.setMinHeight(lp.height);
            }
            radioButton4ThirdNavigate.setSingleLine(true);
            //设置颜色样式
            setNavigateStyle(radioButton4ThirdNavigate);
            radioButton4ThirdNavigate.updateEffDrawable();
            final int idx = i;
            radioButton4ThirdNavigate.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if (isChecked) {
                        currentIndex = idx;
                        changedThirdNavigate(idx);
                    }
                }
            });
            innerRadioGroup.addView(radioButton4ThirdNavigate, lp);
            if (idx == 0) {
                radioButton4ThirdNavigate.setChecked(true);
            }
        }*/
    }

    boolean attached = false;
    boolean checkInited = false;

    @Override
    public void onResume() {
        super.onResume();
        if (!attached && (hadChoosed || navigateIndex == 0)) {
            showContent();
        }
    }

    private void showContent() {
        if (getActivity() == null) return;
//        mViewLine.setVisibility(View.VISIBLE);
//        thirdContainer.setVisibility(View.VISIBLE);
        attached = true;
        checkInited = true;
        setNavigateBgColor();
        removeOld();
        addItems();
    }

    /**
     * 取这个导航是不是在首页中
     *
     * @return
     */
//    private boolean isHomeActivityInstance() {
//        if (getActivity() != null) {
//            String className = getActivity().getClass().getName();
//            return HomePageEntrance.HomeActivityClasses.contains(className);
//        }
//        return false;
//    }

    /**
     * 设置三级导航样式
     *
     * @param radioButton4ThirdNavigate
     */
    int checkedColor;

//    protected void setNavigateStyle(RadioButton4ThirdNavigate radioButton4ThirdNavigate) {
//        int textColor = 0;
//        try {
//            textColor = Color.parseColor(navigate_show_unselected_color);
//        } catch (Exception e) {
//            textColor = getResources().getColor(R.color.light_black_color);
//        }
//        radioButton4ThirdNavigate.setTextColor(textColor);
//        radioButton4ThirdNavigate.uncheckedTextColor = textColor;
//        int color = 0;
//        try {
//            color = Color.parseColor(navigate_show_selected_color);
//        } catch (Exception e) {
//            color = textColor;
//        }
//        radioButton4ThirdNavigate.checkedTextColor = color;
//        checkedColor = radioButton4ThirdNavigate.uncheckedTextColor;
//        if (currentMode == Mode_Rect) {
//            radioButton4ThirdNavigate.checkedBgDrawable = Utility.tintDrawable(radioButton4ThirdNavigate.checkedTextColor, ContextCompat.getDrawable(getActivity(), R.drawable.third_nav_checked_rect));
//            radioButton4ThirdNavigate.uncheckedBgDrawable = Utility.tintDrawable(radioButton4ThirdNavigate.uncheckedTextColor, ContextCompat.getDrawable(getActivity(), R.drawable.third_nav_unchecked_rect));
//        }
//    }

//    protected void changedThirdNavigate(int index) {
//        try {
//            fragmentManager = getChildFragmentManager();
//            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
//            if (currentFragment != null)
//                fragmentTransaction.remove(currentFragment).commitNowAllowingStateLoss();
////            currentFragment=根据导航去实例化找导航 类
//            currentFragment = AppModuleUtils.getViewContentFragment(getActivity(), childNavigates.get(index));
//            fragmentTransaction.replace(R.id.bottomFragment, currentFragment).commitAllowingStateLoss();
//            fragmentManager.executePendingTransactions();
//            if (currentFragment instanceof INaviateState) {
//                ((INaviateState) currentFragment).choosed();
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        outState.putParcelable("catalog", catalogItem);
        super.onSaveInstanceState(outState);
    }

    @Override
    public void onDetach() {
        super.onDetach();
        /*try {
            Field childFragmentManager = Fragment.class.getDeclaredField("mChildFragmentManager");
            childFragmentManager.setAccessible(true);
            childFragmentManager.set(this, null);
        } catch (Exception e) {
            e.printStackTrace();
        }*/
    }

    @Override
    public void onDestroy() {
        removeOld();
        super.onDestroy();
    }

    protected void removeOld() {
       /* if (getActivity() != null && currentFragment != null) {
            try {
                FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
                transaction.remove(currentFragment).commitAllowingStateLoss();
                getChildFragmentManager().executePendingTransactions();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        currentFragment = null;*/
    }

    public final void setNavigateBgColor() {
        int bgColor;
        try {
            bgColor = Color.parseColor(background_color);
        } catch (Exception e) {
            bgColor = getResources().getColor(R.color.white);
        }
        setNavigateBgColor(bgColor);
    }

    public final void setNavigateBgColor(int color) {
        //  ourScrollView.setBackgroundColor(color);
        tabbg.setBackgroundColor(color);
//        tabLayout.setBackgroundColor(color);
    }

    @Override
    public void onViewCreated(@NotNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        view.setTag(R.id.thirdNavTag, this);
        SecondFloorHandlerKt.navPaddingTopMatch(this);
    }

    boolean handled = false;

    @Override
    public void fullScreenSize(boolean value) {
        if (currentMode != Mode_Rect || handled) return;
        handled = true;
       /* thirdContainer.setNeedClip(value);
        thirdContainer.postInvalidate();
        int color = Utility.mergeColor(checkedColor, Utility.getTransParent(0.2F));
        Drawable drawabe = DefaultBgUtil.generateRoundStrokeShapeDrawable(getActivity().getResources().getDimensionPixelSize(R.dimen.dimen45), getActivity().getResources().getDimension(R.dimen.dimen1), color);
        if (!value) {
            innerRadioGroup.color = color;
//            innerRadioGroup.needDraw=true;
            innerRadioGroup.needDraw = false;
            innerRadioGroup.radius = getActivity().getResources().getDimensionPixelSize(R.dimen.dimen45);
            innerRadioGroup.postInvalidate();
        } else {
            ourScrollView.setBackground(drawabe);
        }*/


    }

    boolean isContainsShanshiping = false;

    @Override
    public void onPause() {
        if (isContainsShanshiping) {
            EventBus.getDefault().post(new OnVideoPause());
        }
        super.onPause();
    }
}